//
//  BZUserAccountViewModel.swift
//  weibo
//
//  Created by zzx on 2017/7/30.
//  Copyright © 2017年 zzx. All rights reserved.
//

import UIKit

class BZUserAccountViewModel: NSObject {

    //设置全局单例
    static let sharedViewModel: BZUserAccountViewModel = BZUserAccountViewModel()
    
    private override init() {
        super.init()
        
        userAccount = BZUserAccount.loadUserAccount()
        
    }
    
    //应用模型
    var userAccount: BZUserAccount?
    
    //是否登陆成功标记
    var isLogin: Bool {
    
        return accessToken != nil
    
    }
    
    //获取token
    var accessToken: String? {
        
        guard let token = userAccount?.access_token else {
            
            return nil
            
        }
        
        let result = userAccount?.expiresDate?.compare(Date())
        
        if result == ComparisonResult.orderedDescending {
            //表示没过期
            return token
        }
        
        return nil
        
    }
    
    

    //MARK:- 通过授权码获取令牌
    func requestAccessToken(code: String , callBack: @escaping (Bool)->()) {
        
        BZNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            
            if error != nil {
                
                print("error: \(error!)")
                
                return
                
            }
            
            //转成字典
            let dic = response as! [String: Any]
            
            //字典转模型
            let userAccount = BZUserAccount(dic: dic)
            
            
            
            self.requsetUserInfo(userAccount: userAccount, callBack: callBack)
        }
    }
    
    //MARK:- 获取用户信息
    private func requsetUserInfo(userAccount: BZUserAccount, callBack: @escaping (Bool)->()) {
        
        //令牌
        let token = userAccount.access_token!
        
        //用户id
        let uid = userAccount.uid
        
        BZNetworkTools.sharedTools.requestUserInfo(accessToken: token, uid: uid) { (response, error) in
            
            if error != nil {
                
                print("error\(error!)")
                
                return
            }
            
            //转成字典
            let dic = response as! [String: Any]
            
            //给对象赋值
            userAccount.name = dic["name"] as? String
            
            userAccount.avatar_large = dic["avatar_large"] as? String
            
            
            //登陆成功
            userAccount.saveUseAccount()
            
            //记录用户模型
            self.userAccount = userAccount
            
            callBack(true)
            
            
        }
    }
    
}
